package com.hw.nio.selector;


import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * @author 车宏伟
 * @date 2021/1/13 11:31
 * UDP数据传输
 */
public class DatagramChannelSelector {

    /**
     * 创建 selector
     * 创建UDP通道，绑定端口
     * 注册selector，并且绑定事件
     * while true 阻塞，selector() 方法获取事件，监控就绪事件
     * 获取 selectKeys ，从selectionKey中获取管道，读写数据，执行业务操作
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        // 创建selector
        Selector selector = Selector.open();
        // 创建UDP通道
        DatagramChannel channel = DatagramChannel.open();
        // 绑定端口号
        channel.bind(new InetSocketAddress(8888));
        // 设置非阻塞模式
        channel.configureBlocking(false);
        // 注册读事件
        channel.register(selector, SelectionKey.OP_READ);
        while (true){
            int count = selector.select();
            if(count > 0){
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                ByteBuffer buffer = ByteBuffer.allocate(1024);;
                while (iterator.hasNext()){
                    SelectionKey next = iterator.next();
                    DatagramChannel channel1 = (DatagramChannel) next.channel();
                    channel1.receive(buffer);
                    buffer.flip();
                    byte[]arr = new byte[buffer.remaining()];
                    buffer.get(arr);
                    System.out.println(new String(arr, Charset.defaultCharset()));
                    iterator.remove();
                }
            }
        }

    }

}
